package com.zhangkunhao.notes.web.servlet;

import com.alibaba.fastjson.JSON;
import com.zhangkunhao.notes.entity.Do.PrivateMessage;
import com.zhangkunhao.notes.entity.bo.Message;
import com.zhangkunhao.notes.entity.bo.PageBean;
import com.zhangkunhao.notes.service.PrivateMessageServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 私信的controller
 *
 * @author 20642
 */
@WebServlet("/privateMessage/*")
public class PrivateMessageServlet extends BaseDaoServlet {
    private PrivateMessageServiceImpl messageService = new PrivateMessageServiceImpl();

    public void sendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.接收提出的问题的数据
        String params = request.getReader().readLine();

        //2.转为对象
        PrivateMessage message = JSON.parseObject(params, PrivateMessage.class);
        System.out.println(message + "控制层的message");

        //3.调用service层
        Message<PrivateMessage> messageMessage = messageService.sendMessage(message);
        System.out.println("sendMessage:" + messageMessage);

        //4.转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(messageMessage));
    }

    public void readMySendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 通过Session接收登录的用户id
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //调用service层,封装返回前端的对象
        PageBean<PrivateMessage> messagePageBean = messageService.readMySendMessage(userId);

        // 转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(messagePageBean));
    }

    public void readMyGetMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 通过Session接收登录的用户id
        Integer userId = (Integer) request.getSession().getAttribute("userId");

        //调用service层,封装返回前端的对象
        PageBean<PrivateMessage> messagePageBean = messageService.readMyGetMessage(userId);

        // 转换为json数据,写数据
        response.setContentType("text/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(messagePageBean));
    }

}
